

import java.util.ArrayList;
import java.util.List;

/**
 * Time: 2/25/21 3:51 PM
 * Author: leixun
 * Desc:
 *
 */

// 一条句子结束
//碰到N个单词
//    匹配所有句子的这N个 单词
//    for(i=0;i<sentence.size;i++){
//        if(匹配上){
//            for(sentence 中所有单词){
//                查找正文下一个单词 是否匹配
//            }
//            if(全部匹配上){
//                决定插入sentenceTag
//                记住索引
//            } else{
//                没有 则循环下一个句子
//            }
//        } else {
//            则循环下一个句子
//        }
//    }
//    整理数据并插入
//    跳到上一次插入索引的地方 继续循环


public class InsertSentenceTagUtils {
    public static String insertSentenceTagIntoSrc(String srcData, ArrayList<LrcBean> lrcBeans){
        StringBuilder resultSrcData = new StringBuilder();
        int length = srcData.length();
        boolean isStartHtmlTag = false;
        StringBuilder sentenceTempSb = new StringBuilder();
        int jumpReadIndex = -1;
        LrcBean lrcBean = null;
        String sentenceTag = "<sentence id=\"";
        boolean startOutCustomTag = false;

        // &nbsp; 处理 [#paragraph] [#insert] 处理
        for(int i = 0 ;i<length;i++){
            char charSrc = srcData.charAt(i);
            if('[' == charSrc){
                StringBuilder customTagPre = new StringBuilder();
                for(int k=i;k<i+5 && k<length;k++){
                    customTagPre.append(srcData.charAt(k));
                }
                if("[#par".equals(customTagPre.toString())
                        || "[#ins".equals(customTagPre.toString())
                        || "[/hig".equals(customTagPre.toString())
                        || "[#hig".equals(customTagPre.toString())
                    ){
                    startOutCustomTag = true;
                }
            }
            if(']' == charSrc){
                startOutCustomTag = false;
                resultSrcData.append(charSrc);
                continue;
            }
            if(startOutCustomTag){
                resultSrcData.append(charSrc);
                continue;
            }
            if(charSrc == '<'){
                if(!isEmpty(sentenceTempSb.toString())){
                   resultSrcData.append(sentenceTempSb);
                   sentenceTempSb = new StringBuilder();
                }
                isStartHtmlTag = true;
                resultSrcData.append(charSrc);
            }else{
                if(charSrc == '>'){
                    resultSrcData.append(charSrc);
                    isStartHtmlTag = false;
                }else{
                    if(isStartHtmlTag){
                        resultSrcData.append(charSrc);
                    }else{
                        // 塞入原文文本
                        StringBuilder nextWords = new StringBuilder();
                        nextWords.append(sentenceTempSb.toString());
                        // 查到一个字符 一定要找到完整句子 . ! ? [#pargraph] [insert] 结束
                        boolean startCustomTag = false;
                        boolean startTag =false;
                        jumpReadIndex = -1;
                        boolean startWasteTag = false;
                        for(int j = i;j<length;j++){
                            char charNextSrc = srcData.charAt(j);
                            if('>' == charNextSrc){
                                startTag = false;
                                continue;
                            }else{
                                if(startTag){
                                    // 索引还在标签内容处 继续读
                                    continue;
                                }
                            }
                            if('[' == charNextSrc){
                                StringBuilder customTagPre = new StringBuilder();
                                for(int k=j;k<j+4 && k<length;k++){
                                    customTagPre.append(srcData.charAt(k));
                                }
                                if("[#pa".equals(customTagPre.toString())
                                    || "[#in".equals(customTagPre.toString())
                                    ){
                                    startCustomTag = true;
                                }
                                if("[#hi".equals(customTagPre.toString())
                                    || "[/hi".equals(customTagPre.toString())){
                                    startWasteTag = true;
                                }
                            }
                            if(']' == charNextSrc && startWasteTag){
                                startWasteTag = false;
                                continue;
                            }
                            jumpReadIndex = j;
                            if(startCustomTag || '.' == charNextSrc || '!' == charNextSrc || '?' == charNextSrc){
                                break;
                            }else{
                                if('<' == charNextSrc){
                                    startTag= true;
                                    continue;
                                }else if(startWasteTag){
                                    continue;
                                }
                            }


                            nextWords.append(charNextSrc);
                        }
                        if(jumpReadIndex-i>0){
                            if(isEmpty(cleanSentenceSpace(nextWords.toString()))){
                                String jumpStr = srcData.substring(i,jumpReadIndex);
                                resultSrcData.append(jumpStr);
                                i = jumpReadIndex-1;
                                continue;
                            }
                            lrcBean = getSentenceTranslate(nextWords.toString(),lrcBeans);
                            if(lrcBean == null){
                                System.out.println("rrrrrrr"+resultSrcData.toString());
                                String d = "<h2 style=\"text-align:center;\"><strong><sentence id=\"95505\" end=\"123\">The Commercialization of Lumber</strong></h2> <p style=\"text-align:center;\"></p> <p>[#paragraph1]<sentence id=\"95506\" end=\"218\">In nineteenth-century America, practically everything that was built involved wood.<sentence id=\"95507\" end=\"272\"> Pine was especially attractive for building purposes.<sentence id=\"95508\" end=\"398\"> It is [#highlight1]durable[/highlight1] and strong, yet soft enough to be easily worked with even the simplest of hand tools.<sentence id=\"95509\" end=\"503\"> It also floats nicely on water, which allowed it to be transported to distant markets across the nation.<sentence id=\"95510\" end=\"748\"> The central and northern reaches of the Great Lakes states—Michigan, Wisconsin, and Minnesota—all contained extensive pine forests as well as many large rivers for floating logs into the Great Lakes, from where they were transported nationwide.<br>&nbsp;</p> <p>[#paragraph2]<sentence id=\"95511\" end=\"946\">By 1860, the settlement of the American West along with timber shortages in the East converged with ever-widening impact on the pine forests of the Great Lakes states.<sentence id=\"95512\" end=\"1052\"> Over the next 30 years, lumbering became a full-fledged enterprise in Michigan, Wisconsin, and Minnesota.<sentence id=\"95513\" end=\"1170\"> Newly formed lumbering corporations bought up huge tracts of pineland and set about systematically cutting the trees.<sentence id=\"95514\" end=\"1364\"> Both the colonists and the later industrialists saw timber as a [#highlight3]commodity[/highlight3], but the latter group adopted a far more thorough and calculating approach to removing trees.<sentence id=\"95515\" end=\"1462\"> In this sense, what happened between 1860 and 1890 represented a significant break with the past.<sentence id=\"95516\" end=\"1576\"> No longer were farmers in search of extra income the main source for shingles, firewood, and other wood products.<sentence id=\"95517\" end=\"1776\"> By the 1870s, farmers and city dwellers alike purchased forest products from large manufacturing companies located in the Great Lakes states rather than chopping wood themselves or buying it locally.<br>&nbsp;</p> <p>[#paragraph3]<sentence id=\"95518\" end=\"1890\">The commercialization of lumbering was in part the product of technological change.<sentence id=\"95519\" end=\"2049\"> The early, thick saw blades tended to waste a large quantity of wood, with perhaps as much as a third of the log left behind on the floor as sawdust or scrap.<sentence id=\"95520\" end=\"2220\"> In the 1870s, however, [#highlight5]the British-invented band saw,[/highlight5] with its thinner blade, became standard issue in the Great Lakes states’ lumber factories.<sentence id=\"95521\" end=\"2395\"> Meanwhile, the rise of steam-powered mills streamlined production by [#highlight6]allowing for[/highlight6] the more efficient, centralized, and continuous cutting of lumber.<sentence id=\"95522\" end=\"2484\"> Steam helped to automate a variety of tasks, from cutting to the carrying away of waste.<sentence id=\"95523\" end=\"2609\"> Mills also employed steam to heat log ponds, preventing them from freezing and making possible year-round lumber production.<br>&nbsp;</p> <p>[#paragraph4]<sentence id=\"95524\" end=\"2754\">For industrial lumbering to succeed, a way had to be found to neutralize the effects of the seasons on production.<sentence id=\"95525\" end=\"2894\"> Traditionally, cutting took place in the winter, when snow and ice made it easier to drag logs on sleds or sleighs to the banks of streams.<sentence id=\"95526\" end=\"3010\"> Once the streams and lakes thawed, workers rafted the logs to mills, where they were cut into lumber in the summer. [#insert1]<sentence id=\"95527\" end=\"3145\">&nbsp;If nature did not cooperate—if the winter proved dry and warm, if the spring thaw was delayed—production would suffer.<sentence id=\"95528\" end=\"3292\"> To counter the effects of climate on lumber production, loggers experimented with a variety of techniques for transporting trees out of the woods. [#insert2]<sentence id=\"95529\" end=\"3477\"> In the 1870s, loggers in the Great Lakes states began sprinkling water on sleigh roads, giving them an artificial ice coating to [#highlight8]facilitate[/highlight8] travel. [#insert3]<sentence id=\"95530\" end=\"3571\"> The ice reduced the friction and allowed workers to move larger and heavier loads. [#insert4]<br>&nbsp;</p> <p>[#paragraph5]<sentence id=\"95531\" end=\"3706\">But all the sprinkling in the world would not save a logger from the threat of a warm winter.<sentence id=\"95532\" end=\"3751\"> Without snow the sleigh roads turned to mud.<sentence id=\"95533\" end=\"3871\"> In the 1870s, a set of snowless winters left lumber companies to ponder ways of liberating themselves from the seasons.<sentence id=\"95534\" end=\"3903\"> Railroads were one possibility.<sentence id=\"95535\" end=\"4023\"> At first, the [#highlight10]remoteness[/highlight10] of the pine forests discouraged common carriers from laying track.<sentence id=\"95536\" end=\"4152\"> But increasing lumber prices in the late 1870s combined with periodic warm, dry winters compelled loggers to turn to iron rails.<sentence id=\"95537\" end=\"4272\"> By 1887, 89 logging railroads crisscrossed Michigan, transforming logging from a winter activity into a year-round one.<br>&nbsp;</p> <p>[#paragraph6]<sentence id=\"95538\" end=\"4400\">Once the logs arrived at a river, the trip downstream to a mill could be a long and tortuous one.<sentence id=\"95539\" end=\"4613\"> Logjams (buildups of logs that prevent logs from moving downstream) were common—at times stretching for 10 miles—and became even more frequent as pressure on the northern Midwest pinelands increased in the 1860s.<sentence id=\"95540\" end=\"4773\"> To help keep the logs moving efficiently, barriers called booms (essentially a chain of floating logs) were constructed to control the direction of the timber.<sentence id=\"95541\" end=\"4868\"> By the 1870s, lumber companies existed in all the major logging areas of the northern Midwest.</p>";
                                System.out.println("nnnnnnn"+nextWords.toString());
                            }
                            resultSrcData.append(sentenceTag+lrcBean.getId()+"\" end=\""+jumpReadIndex+"\">");
                            String jumpStr = "";
                            if(startCustomTag){
                                jumpStr = srcData.substring(i,jumpReadIndex);
                                i = jumpReadIndex-1;
                            }else{
                                if(jumpReadIndex+1>=length){
                                    jumpStr = srcData.substring(i,jumpReadIndex);
                                    i = jumpReadIndex-1;
                                }else{
                                    jumpStr = srcData.substring(i,jumpReadIndex+1);
                                    i = jumpReadIndex;
                                }
                            }
                            resultSrcData.append(jumpStr);
                            isStartHtmlTag = false;
                            lrcBean = null;
                            sentenceTempSb = new StringBuilder();
                            continue;
                        }
                    }
                }
            }

        }
        System.out.println(resultSrcData.toString());
        return "";
    }

    public static boolean isEmpty( CharSequence str) {
        return str == null || str.length() == 0;
    }

    public static LrcBean getSentenceTranslate(String sentence,List<LrcBean> mLrcBeans) {
        if (sentence != null) {
            int lrcSize = mLrcBeans.size();
            for (int i = 0; i < lrcSize; i++) {
                LrcBean bean = mLrcBeans.get(i);
                String sentenceOriginal = cleanSentenceSpace(bean.getEntext());
                String sentenceSelected = cleanSentenceSpace(sentence);
                boolean isFind = false;
                if (sentenceOriginal.length() == sentenceSelected.length()
                        && sentenceOriginal.equals(sentenceSelected)) {
                    isFind = true;
                }
                if (isFind) {
                    return mLrcBeans.get(i);
                }
            }
        }
        return null;
    }

    public static String cleanSentenceSpace(CharSequence cs){
        if(cs == null){
            return "";
        } else {
            cs = cs.toString().replaceAll("&nbsp;"," ");
            char[] chars = cs.toString().toCharArray();
            StringBuilder sb = new StringBuilder();
            for(int i = 0;chars!=null && i<chars.length;i++){
                if(Character.isLetter(chars[i])){
                    sb.append(chars[i]);
                }
            }
            return sb.toString();
        }
    }
}


